package com.molinari.coding.activities.addconto;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.molinari.coding.Cella;
import com.molinari.coding.ControllerCoding;
import com.molinari.coding.R;
import com.molinari.coding.activities.CodingBaseActivity;
import com.molinari.coding.dati.domain.dao.WrapCella;

public class AggiungiContoActivity extends CodingBaseActivity {

	private Button btnAddConto;
	
	@Override
	protected int getIdLayout() {
		return R.layout.aggiungiconto;
	}

	@Override
	protected void onCreateCustom(Bundle savedInstanceState) throws Exception {
		
		addListener();
		
		final boolean nonCreato = !ControllerCoding.hasConto(getApplicationContext());
		final HashMap<String, com.molinari.coding.dati.domain.Cella> mapCelle = mappaCelleEistenti();
		final Cella[] celle = riempiCelle(mapCelle);
		
		btnAddConto = loadButton(btnAddConto, R.id.btnAddConto);
		btnAddConto.setOnClickListener(new View.OnClickListener() {
			
			
			
			@Override
			public void onClick(View v) {
				
				Cella[] celleInner = aggiornaCelle(celle);
				
				
//				if(checkCelle(celle)){
					
					boolean caricamentoOk = true;
					try{
						for (int i = 0; i < celleInner.length; i++) {

							Cella cella = celleInner[i];
							com.molinari.coding.dati.domain.Cella cellaDom = new com.molinari.coding.dati.domain.Cella();
							cellaDom.setChiave(cella.getChiave());
							if(cella.getUno() != null){
							cellaDom.setUno(cella.getUno());
							cellaDom.setDue(cella.getDue());
							cellaDom.setTre(cella.getTre());
							cellaDom.setIdUtente(ControllerCoding.getSingleton().getUtenteLogin().getidUtente());
								if(!mapCelle.containsKey(cella.getChiave())){
									boolean insert = new WrapCella(getApplicationContext()).insert(cellaDom);
									if(!insert){
										caricamentoOk = false;
									}
								}else{
									boolean update = new WrapCella(getApplicationContext()).update(cellaDom);
									if(!update){
										caricamentoOk = false;
									}
								}
							}
						}
						if(checkCelle(celle)){
							ControllerCoding.signContoAsCreated();
						}
					}catch (Exception e) {
						caricamentoOk = false;
						Log.e("Errore creando le celle", e.toString());
					}
					if(caricamentoOk){
						Toast.makeText(getApplicationContext(), "Inserimento dati completato", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(getApplicationContext(), "Qualcosa è andato storto, riprova", Toast.LENGTH_SHORT).show();
					}
//				}else{
//					Toast.makeText(getApplicationContext(), "Completa tutte le celle", Toast.LENGTH_SHORT).show();
//				}
			}

			
		});
	}
	
	private Cella[] aggiornaCelle(Cella[] celle) {
		
		if(celle != null){
			for (int i = 0; i < celle.length; i++) {
				Cella cella = celle[i];
				cella.setChiave(Integer.toString(i+1));
				int id = getEditIdByIdName(i + 1);
				EditText edit = null;
				edit = loadEdit(edit,id);
				
				if(edit != null && edit.getText() != null){
					
					String testoEdit = edit.getText().toString();
					
					if(testoEdit.length() == 3){
						cella.setUno(testoEdit.substring(0, 1));
						cella.setDue(testoEdit.substring(1, 2));
						cella.setTre(testoEdit.substring(2, 3));
					}
				}
				
			}
		}
		return celle;
	}
	
	private Cella[] riempiCelle(HashMap<String,com.molinari.coding.dati.domain.Cella> mapCelle) {
		
		Cella[] celle = creaArray(mapCelle);
		
		for (int i = 0; i < celle.length; i++) {
			Cella cella = celle[i];
			cella.setChiave(Integer.toString(i+1));
			int id = getEditIdByIdName(i + 1);
			EditText edit = null;
			edit = loadEdit(edit,id);
			
			String uno = cella.getUno();
			String due = cella.getDue();
			String tre = cella.getTre();
			if(uno != null && due != null && tre != null){
				edit.setText(uno + due + tre);
			}
			
//			if(edit != null && edit.getText() != null){
//				
//				String testoEdit = edit.getText().toString();
//				
//				if(testoEdit.length() == 3){
//					cella.setUno(testoEdit.substring(0, 1));
//					cella.setDue(testoEdit.substring(1, 2));
//					cella.setTre(testoEdit.substring(2, 3));
//				}
//			}
			
		}
		return celle;
	}
	
	private HashMap<String, com.molinari.coding.dati.domain.Cella> mappaCelleEistenti() {
		HashMap<String, com.molinari.coding.dati.domain.Cella> mapCelle = new HashMap<String, com.molinari.coding.dati.domain.Cella>();

		int idUtente = ControllerCoding.getSingleton().getUtenteLogin().getidUtente();
		Iterator<com.molinari.coding.dati.domain.Cella> iterCelle = (Iterator<com.molinari.coding.dati.domain.Cella>) new WrapCella(getApplicationContext()).selectByIdUtente(idUtente);
		if(iterCelle != null){
			while (iterCelle.hasNext()) {
				com.molinari.coding.dati.domain.Cella cellaDom = (com.molinari.coding.dati.domain.Cella) iterCelle.next();
				mapCelle.put(cellaDom.getChiave(), cellaDom);
			}
		}
		return mapCelle;
	}
	
	private int getEditIdByIdName(int idName){
		
		Log.i("Prova", "Sono Entrato!");
		
		if(idName == 1){
			return R.id.t1;
		}else if(idName == 2){
			return R.id.t2;
		}else if(idName == 3){
			return R.id.t3;
		}else if(idName == 4){
			return R.id.t4;
		}else if(idName == 5){
			return R.id.t5;
		}else if(idName == 6){
			return R.id.t6;
		}else if(idName == 7){
			return R.id.t7;
		}else if(idName == 8){
			return R.id.t8;
		}else if(idName == 9){
			return R.id.t9;
		}else if(idName == 10){
			return R.id.t10;
		}else if(idName == 11){
			return R.id.t11;
		}else if(idName == 12){
			return R.id.t12;
		}else if(idName == 13){
			return R.id.t13;
		}else if(idName == 14){
			return R.id.t14;
		}else if(idName == 15){
			return R.id.t15;
		}else if(idName == 16){
			return R.id.t16;
		}else if(idName == 17){
			return R.id.t17;
		}else if(idName == 18){
			return R.id.t18;
		}else if(idName == 19){
			return R.id.t19;
		}else if(idName == 20){
			return R.id.t20;
		}else if(idName == 21){
			return R.id.t21;
		}else if(idName == 22){
			return R.id.t22;
		}else if(idName == 23){
			return R.id.t23;
		}else if(idName == 24){
			return R.id.t24;
		}
		return 0;
	}
	
	private void addListener() {
		for (int i = 0; i < 24; i++) {
			int id = getEditIdByIdName(i + 1);
			
			EditText edit = null;
			edit = loadEdit(edit,id);
			if(edit != null){
				edit.addTextChangedListener(new TextWatcherMy(i));
			}
		}
		
	}
	
	private class TextWatcherMy implements TextWatcher{

		int i;
		
		TextWatcherMy(int i){
			this.i = i;
		}
		
		@Override
		public void afterTextChanged(Editable s) {}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,int after) {}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if(s.length() == 3){
				
				final int idNext = getEditIdByIdName(i + 2);
				View editNext = null;
				editNext = load(editNext,idNext);
				editNext.requestFocus();
			}
			
		}
		
	}

	private boolean checkCelle(final Cella[] celle) {
		boolean ret = true;
		
		for (int i = 0; i < celle.length; i++) {
			
			Cella cella = celle[i];
			if(cella != null){
				if(cella.getUno() == null || cella.getUno().trim().equals("") ||
				   cella.getDue() == null || cella.getDue().trim().equals("") ||
				   cella.getTre() == null || cella.getTre().trim().equals("")) {
					
					return false;
				}
			}
		}
		return ret;
	}
	
	public Cella[] creaArray(HashMap<String, com.molinari.coding.dati.domain.Cella> mapCelle){

		ArrayList<Cella> celle = new ArrayList<Cella>();
		for (int i = 1; i <= 24; i++) {
			Cella cella = new Cella();

			String chiave = Integer.toString(i);
			cella.setChiave(chiave);

			com.molinari.coding.dati.domain.Cella cellaDom = mapCelle.get(chiave);
			if(cellaDom != null){
				cella.setUno(cellaDom.getUno());
				cella.setDue(cellaDom.getDue());
				cella.setTre(cellaDom.getTre());
			}
			celle.add(cella);
		}

		Collections.sort(celle, new Comparator<Cella>() {
			public int compare(Cella cella1, Cella cella2) {
				return new Integer(cella1.getChiave()).compareTo(new Integer(cella2.getChiave()));
			};
		});

		return celle.toArray(new Cella[celle.size()]);
	}
}
